<template>
  <view class="refund-container">
    <!-- 页面标题 -->
    <view class="page-header">
      <text class="page-title">退款订单</text>
      <text class="page-subtitle">共 {{ totalOrders }} 笔退款订单</text>
    </view>

    <!-- 订单列表 -->
    <view class="refund-list">
      <view class="refund-item" v-for="(item, index) in refundOrders" :key="item.id">
        <view style="display: flex; align-items: center; justify-content: space-around">
          <image style="width: 200rpx; height: 200rpx" :src="IMG_URL + item.ebMerActivityTicket.icon" mode="scaleToFill" />
          <view>
            <view class="item-header">
              <view class="order-basic">
                <text class="order-no"> {{ item.ebMerActivityTicket.name }}</text>
                <u-tag :text="getStatusText(item.refundStatus)" :type="getStatusType(item.refundStatus)" size="mini" shape="circle" />
              </view>
              <view class="order-time">{{ formatTime(item.createTime) }}</view>
            </view>

            <view class="item-content">
              <view class="order-info">
                <view class="info-item">
                  <text class="info-label">订单类型:</text>
                  <text class="info-value">{{ item.orderTypeStr }}</text>
                </view>
                <view class="info-item">
                  <text class="info-label">退款金额:</text>
                  <text class="info-value price">¥{{ item.payPrice }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>

        <view class="item-footer">
          <view class="action-buttons">
            <u-button
              v-if="item.refundStatus === 1"
              type="error"
              size="small"
              shape="circle"
              :loading="item.confirming"
              :disabled="item.confirming"
              @click="confirmRefund(item, index)"
            >
              {{ item.confirming ? '处理中...' : '确认退款' }}
            </u-button>
            <u-button v-else type="info" size="small" shape="circle" disabled>
              {{ getStatusText(item.refundStatus) }}
            </u-button>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-if="!loading && refundOrders.length === 0">
        <u-empty mode="order" text="暂无退款订单" icon="http://36.139.124.9:9000/community/img/empty.png"> </u-empty>
      </view>

      <!-- 加载状态 -->
      <view class="loading-state" v-if="loading">
        <u-loading-icon mode="circle" size="24" />
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 底部提示 -->
      <view class="end-tip" v-if="loadend && refundOrders.length > 0">
        <u-icon name="file-text" size="24" />
        <text class="end-text">没有更多数据了</text>
      </view>
    </view>
  </view>
</template>

<script>
import { orderlistBusiness, refundConfirm } from '../../../utils/merorder/mer';
import { IMG_URL } from '../../../config/index.js';

export default {
  data() {
    return {
      userInfo: uni.getStorageSync('userInfo'),
      loading: false,
      loadend: false,
      refundOrders: [],
      page: 1,
      limit: 20,
      totalOrders: 0,
      IMG_URL
    };
  },

  onLoad() {
    this.initData();
  },

  onShow() {
    this.initData();
  },

  methods: {
    // 初始化数据
    initData() {
      this.page = 1;
      this.refundOrders = [];
      this.loadend = false;
      this.getRefundOrders();
    },

    // 获取退款订单列表
    getRefundOrders() {
      if (this.loadend) return;
      if (this.loading) return;
      this.loading = true;

      orderlistBusiness({
        type: -3, // 退款订单类型
        page: this.page,
        limit: this.limit,
        ebMerId: this.userInfo.merId
      })
        .then((res) => {
          const list = res.data.list || [];
          const total = res.data.total || 0;

          // 更新总订单数
          this.totalOrders = total;

          // 处理订单数据
          const processedList = list.map((item) => ({
            ...item,
            confirming: false // 添加确认状态标识
          }));

          // 判断是否加载完所有数据
          this.loadend = list.length < this.limit;

          // 合并数据
          this.refundOrders = this.refundOrders.concat(processedList);

          this.loading = false;
          this.page++;
        })
        .catch((err) => {
          this.loading = false;
          uni.showToast({
            title: '数据加载失败',
            icon: 'none'
          });
          console.error('获取退款订单失败:', err);
        });
    },

    // 确认退款
    confirmRefund(item, index) {
      if (!item.id) {
        return uni.showToast({
          title: '缺少订单号无法确认退款',
          icon: 'none'
        });
      }

      // 防止重复点击
      if (item.confirming) return;

      // 设置确认状态
      this.$set(this.refundOrders[index], 'confirming', true);

      uni.showModal({
        title: '确认退款',
        content: `确认要退款 ¥${item.payPrice} 给用户吗？`,
        success: (res) => {
          if (res.confirm) {
            this.processRefund(item, index);
          } else {
            // 取消确认状态
            this.$set(this.refundOrders[index], 'confirming', false);
          }
        },
        fail: () => {
          // 取消确认状态
          this.$set(this.refundOrders[index], 'confirming', false);
        }
      });
    },

    // 处理退款逻辑
    processRefund(item, index) {
      refundConfirm({
        orderId: item.id,
        orderNo: item.orderId,
        amount: item.payPrice
      })
        .then((res) => {
          if (res.code == 200) {
            uni.showToast({
              title: '退款成功',
              icon: 'success'
            });
            // 更新订单状态
            this.$set(this.refundOrders[index], 'refundStatus', 2);
            this.$set(this.refundOrders[index], 'confirming', false);
          } else {
            uni.showToast({
              title: '退款失败，已分账,请线下处理',
              icon: 'none'
            });
            this.$set(this.refundOrders[index], 'confirming', false);
          }
        })
        .catch((err) => {
          uni.showToast({
            title: '退款失败，请联系管理员',
            icon: 'none'
          });
          console.error('退款失败:', err);
          // 取消确认状态
          this.$set(this.refundOrders[index], 'confirming', false);
        });
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        1: '待确认',
        2: '已退款',
        3: '已拒绝'
      };
      return statusMap[status] || '未知状态';
    },

    // 获取状态类型（用于u-tag颜色）
    getStatusType(status) {
      const typeMap = {
        1: 'warning', // 待确认 - 橙色
        2: 'success', // 已退款 - 绿色
        3: 'error' // 已拒绝 - 红色
      };
      return typeMap[status] || 'info';
    },

    // 格式化时间
    formatTime(time) {
      if (!time) return '';
      return time.replace('T', ' ').substring(0, 16);
    },

    // 滚动到底部加载更多
    onReachBottom() {
      this.getRefundOrders();
    }
  }
};
</script>

<style lang="scss" scoped>
.refund-container {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20rpx;
  box-sizing: border-box;
  padding-bottom: 20rpx;
}

.page-header {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);

  .page-title {
    display: block;
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 10rpx;
  }

  .page-subtitle {
    font-size: 28rpx;
    color: #999;
  }
}

.refund-list {
  padding-bottom: 20rpx;
}

.refund-item {
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  padding: 30rpx;
  box-sizing: border-box;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;

  &:active {
    transform: translateY(2rpx);
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  }
}

.item-header {
  border-bottom: 1rpx solid #f0f0f0;
  padding-bottom: 20rpx;
  margin-bottom: 20rpx;

  .order-basic {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10rpx;

    .order-no {
      font-size: 28rpx;
      color: #333;
      font-weight: bold;
    }
  }

  .order-time {
    font-size: 24rpx;
    color: #999;
  }
}

.item-content {
  padding: 10rpx 0;

  .order-info {
    .info-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 15rpx;

      .info-label {
        font-size: 28rpx;
        color: #666;
      }

      .info-value {
        font-size: 28rpx;
        color: #333;

        &.price {
          font-weight: bold;
          color: #e93323;
        }
      }
    }
  }
}

.item-footer {
  padding-top: 20rpx;
  border-top: 1rpx solid #f0f0f0;

  .action-buttons {
    display: flex;
    justify-content: flex-end;
  }
}

.empty-state {
  padding: 100rpx 0;
  text-align: center;
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 30rpx;

  .loading-text {
    margin-left: 16rpx;
    font-size: 28rpx;
    color: #999;
  }
}

.end-tip {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 30rpx;

  .end-text {
    margin-left: 16rpx;
    font-size: 28rpx;
    color: #999;
  }
}
</style>
